@(issue: Option[gitbucket.core.model.Issue],
  comments: List[gitbucket.core.model.Comment],
  isManageable: Boolean,
  repository: gitbucket.core.service.RepositoryService.RepositoryInfo,
  pullreq: Option[gitbucket.core.model.PullRequest] = None,
  commitId: Option[String] = None,
  renderScript: Boolean = true)(implicit context: gitbucket.core.controller.Context)
@import gitbucket.core.view.helpers
@import gitbucket.core.util.StringUtil._
@issueOrPullRequest()={ @if(issue.exists(_.isPullRequest))( "pull request" )else( "issue" ) }
@showFormattedComment(comment: gitbucket.core.model.IssueComment)={
<div class="panel panel-default issue-comment-box" id="comment-@comment.commentId">
  <div class="panel-heading">
    @helpers.avatarLink(comment.commentedUserName, 20)
    @helpers.user(comment.commentedUserName, styleClass="username strong")
    <span class="muted">
      @if(comment.action == "comment"){
        commented
      } else {
        referenced the @issueOrPullRequest()
      }
      <a href="#comment-@comment.commentId">
        @gitbucket.core.helper.html.datetimeago(comment.registeredDate)
      </a>
    </span>
    @if(comment.action != "commit" && comment.action != "merge" && comment.action != "refer"
    && (isManageable || context.loginAccount.map(_.userName == comment.commentedUserName).getOrElse(false))){
      <span class="pull-right">
        <a href="#" data-comment-id="@comment.commentId"><i class="octicon octicon-pencil" aria-label="Edit"></i></a>&nbsp;
        <a href="#" data-comment-id="@comment.commentId"><i class="octicon octicon-x" aria-label="Remove"></i></a>
      </span>
    }
  </div>
  <div class="panel-body markdown-body" id="commentContent-@comment.commentId">
    @helpers.markdown(
      markdown           = comment.content,
      repository         = repository,
      branch             = repository.repository.defaultBranch,
      enableWikiLink     = false,
      enableRefsLink     = true,
      enableLineBreaks   = true,
      enableTaskList     = true,
      hasWritePermission = isManageable
    )
  </div>
</div>
}
@if(issue.isDefined){
  <div class="panel panel-default issue-comment-box">
    <div class="panel-heading">
      @helpers.avatarLink(issue.get.openedUserName, 20)
      @helpers.user(issue.get.openedUserName, styleClass="username strong")
      <span class="muted">commented @gitbucket.core.helper.html.datetimeago(issue.get.registeredDate)</span>
      <span class="pull-right">
        @if(isManageable || context.loginAccount.map(_.userName == issue.get.openedUserName).getOrElse(false)){
          <a href="#" data-issue-id="@issue.get.issueId"><i class="octicon octicon-pencil" aria-label="Edit"></i></a>
        }
      </span>
    </div>
    <div class="panel-body markdown-body" id="issueContent">
      @helpers.markdown(
        markdown           = issue.get.content getOrElse "No description provided.",
        repository         = repository,
        branch             = repository.repository.defaultBranch,
        enableWikiLink     = false,
        enableRefsLink     = true,
        enableLineBreaks   = true,
        enableTaskList     = true,
        hasWritePermission = isManageable
      )
    </div>
  </div>
}
@comments.map {
  case comment: gitbucket.core.model.IssueComment => {
    @comment.action match {
      case "commit" => {
        @defining({
          val (content, id) = " ([a-f0-9]{40})$".r.findFirstMatchIn(comment.content)
          .map(m => (m.before.toString -> Some(m.group(1))))
          .getOrElse(comment.content -> None)
          val head = content.take(100).takeWhile(_ != '\n')
          (id, head, if(head == content){ None }else{ Some(content.drop(head.length).dropWhile(_ == '\n')) }.filter(_.nonEmpty))
        }){ case (commitId, head, rest) =>
          <div class="discussion-item discussion-item-commit">
            <div class="discussion-item-header">
              <span class="discussion-item-icon"><i class="octicon octicon-bookmark"></i></span>
              @helpers.avatarLink(comment.commentedUserName, 16)
              @helpers.user(comment.commentedUserName, styleClass="username strong")
              added a commit that referenced this @issueOrPullRequest()
              @gitbucket.core.helper.html.datetimeago(comment.registeredDate)
            </div>
            <div style="discussion-item-content">
              @commitId.map{ id =>
                <span class="pull-right"><a href="@context.path/@repository.owner/@repository.name/commit/@id" class="monospace">@id.substring(0, 7)</a></span>
              }
              <span class="discussion-item-content-head"><i class="octicon octicon-git-commit"></i></span>
              @helpers.link(head, repository)
              @rest.map{ content =>
                <a href="javascript:void(0)" class="omit" onclick="$(this.parentNode).find('.discussion-item-content-text').toggle()">...</a>
                <pre class="reset discussion-item-content-text" style="display:none">@helpers.link(content, repository)</pre>
              }
            </div>
          </div>
        }
      }
      case "refer" => {
        <div class="discussion-item discussion-item-refer">
          <div class="discussion-item-header">
            <span class="discussion-item-icon"><i class="octicon octicon-bookmark"></i></span>
            @helpers.avatarLink(comment.commentedUserName, 16)
            @helpers.user(comment.commentedUserName, styleClass="username strong")
            referenced the @issueOrPullRequest()
            @gitbucket.core.helper.html.datetimeago(comment.registeredDate)
          </div>
          <div style="discussion-item-content">
            @defining(comment.content.split(":")){
              case Array(issueId, rest @ _*) => {@helpers.issueLink(repository.owner, repository.name, issueId.toInt, rest.mkString(":"))}
            }
          </div>
        </div>
      }
      case "refer_global" => {
        <div class="discussion-item discussion-item-refer">
          <div class="discussion-item-header">
            <span class="discussion-item-icon"><i class="octicon octicon-bookmark"></i></span>
            @helpers.avatarLink(comment.commentedUserName, 16)
            @helpers.user(comment.commentedUserName, styleClass="username strong")
            referenced the @issueOrPullRequest()
            @gitbucket.core.helper.html.datetimeago(comment.registeredDate)
          </div>
          <div style="discussion-item-content">
          @defining(comment.content.split(":")){
            case Array(issueId, ownerName, repositoryName, rest @ _*) => {
              @helpers.issueGlobalLink(ownerName, repositoryName, issueId.toInt, rest.mkString(":"))
          }}
          </div>
        </div>
      }
      case "merge" => {
        @showFormattedComment(comment)
        <div class="discussion-item discussion-item-merge">
          <div class="discussion-item-header">
            <span class="discussion-item-icon"><i class="octicon octicon-git-merge"></i></span>
            @helpers.avatarLink(comment.commentedUserName, 16)
            @helpers.user(comment.commentedUserName, styleClass="username strong")
            merged commit
            <code>@pullreq.map(_.commitIdTo.substring(0, 7))</code> into
            @if(pullreq.get.requestUserName == repository.owner){
              <code>@pullreq.map(_.branch)</code> from <code>@pullreq.map(_.requestBranch)</code>
            } else {
              <code>@pullreq.map(_.userName):@pullreq.map(_.branch)</code> from <code>@pullreq.map(_.requestUserName):@pullreq.map(_.requestBranch)</code>
            }
            @gitbucket.core.helper.html.datetimeago(comment.registeredDate)
          </div>
        </div>
      }
      case "close" | "close_comment" => {
        @if(comment.action == "close_comment"){
          @showFormattedComment(comment)
        }
        <div class="discussion-item discussion-item-close">
          <div class="discussion-item-header">
            <span class="discussion-item-icon"><i class="octicon octicon-circle-slash"></i></span>
            @helpers.avatarLink(comment.commentedUserName, 16)
            @helpers.user(comment.commentedUserName, styleClass="username strong")
            closed this @issueOrPullRequest()
            @gitbucket.core.helper.html.datetimeago(comment.registeredDate)
          </div>
        </div>
      }
      case "reopen" | "reopen_comment" => {
        @if(comment.action == "reopen_comment"){
          @showFormattedComment(comment)
        }
        <div class="discussion-item discussion-item-reopen">
          <div class="discussion-item-header">
            <span class="discussion-item-icon"><i class="octicon octicon-primitive-dot"></i></span>
            @helpers.avatarLink(comment.commentedUserName, 16)
            @helpers.user(comment.commentedUserName, styleClass="username strong")
            reopened the @issueOrPullRequest()
            @gitbucket.core.helper.html.datetimeago(comment.registeredDate)
          </div>
        </div>
      }
      case "delete_branch" => {
        <div class="discussion-item discussion-item-delete_branch">
          <div class="discussion-item-header">
            <span class="discussion-item-icon"><i class="octicon octicon-git-branch"></i></span>
            @helpers.avatarLink(comment.commentedUserName, 16)
            @helpers.user(comment.commentedUserName, styleClass="username strong")
            deleted the <code>@pullreq.map(_.requestBranch)</code> branch
            @gitbucket.core.helper.html.datetimeago(comment.registeredDate)
          </div>
        </div>
      }
      case "add_label" => {
        <div class="discussion-item discussion-item-add-label">
          <div class="discussion-item-header">
            <span class="discussion-item-icon"><i class="octicon octicon-tag"></i></span>
            @helpers.avatarLink(comment.commentedUserName, 16)
            @helpers.user(comment.commentedUserName, styleClass="username strong")
            added the <code>@comment.content</code> label
            @gitbucket.core.helper.html.datetimeago(comment.registeredDate)
          </div>
        </div>
      }
      case "delete_label" => {
        <div class="discussion-item discussion-item-delete-label">
          <div class="discussion-item-header">
            <span class="discussion-item-icon"><i class="octicon octicon-tag"></i></span>
            @helpers.avatarLink(comment.commentedUserName, 16)
            @helpers.user(comment.commentedUserName, styleClass="username strong")
            removed the <code>@comment.content</code> label
            @gitbucket.core.helper.html.datetimeago(comment.registeredDate)
          </div>
        </div>
      }
      case "change_priority" => {
        <div class="discussion-item discussion-item-change-priority">
          <div class="discussion-item-header">
            <span class="discussion-item-icon"><i class="octicon octicon-flame"></i></span>
            @helpers.avatarLink(comment.commentedUserName, 16)
            @helpers.user(comment.commentedUserName, styleClass="username strong")
            changed priority from <code>@comment.content.split(":")(0)</code> to <code>@comment.content.split(":")(1)</code>
            @gitbucket.core.helper.html.datetimeago(comment.registeredDate)
          </div>
        </div>
      }
      case "change_milestone" => {
        <div class="discussion-item discussion-item-change-milestone">
          <div class="discussion-item-header">
            <span class="discussion-item-icon"><i class="octicon octicon-milestone"></i></span>
            @helpers.avatarLink(comment.commentedUserName, 16)
            @helpers.user(comment.commentedUserName, styleClass="username strong")
            changed milestone from <code>@comment.content.split(":")(0)</code> to <code>@comment.content.split(":")(1)</code>
            @gitbucket.core.helper.html.datetimeago(comment.registeredDate)
          </div>
        </div>
      }
      case "assign" => { @* for backward compatibility *@
        <div class="discussion-item discussion-item-assign">
          <div class="discussion-item-header">
            <span class="discussion-item-icon"><i class="octicon octicon-person"></i></span>
            @helpers.avatarLink(comment.commentedUserName, 16)
            @helpers.user(comment.commentedUserName, styleClass="username strong")
            changed assignee from <code>@comment.content.split(":")(0)</code> to <code>@comment.content.split(":")(1)</code>
            @gitbucket.core.helper.html.datetimeago(comment.registeredDate)
          </div>
        </div>
      }
      case "add_assignee" => {
        <div class="discussion-item discussion-item-assign">
          <div class="discussion-item-header">
            <span class="discussion-item-icon"><i class="octicon octicon-person"></i></span>
            @helpers.avatarLink(comment.commentedUserName, 16)
            @helpers.user(comment.commentedUserName, styleClass="username strong")
            assigned <code>@comment.content</code>
            @gitbucket.core.helper.html.datetimeago(comment.registeredDate)
          </div>
        </div>
      }
      case "delete_assignee" => {
        <div class="discussion-item discussion-item-assign">
          <div class="discussion-item-header">
            <span class="discussion-item-icon"><i class="octicon octicon-person"></i></span>
            @helpers.avatarLink(comment.commentedUserName, 16)
            @helpers.user(comment.commentedUserName, styleClass="username strong")
            unassigned <code>@comment.content</code></code>
            @gitbucket.core.helper.html.datetimeago(comment.registeredDate)
          </div>
        </div>
      }
      case "change_title" => {
        <div class="discussion-item discussion-item-pencil">
          <div class="discussion-item-header">
            <span class="discussion-item-icon"><i class="octicon octicon-pencil"></i></span>
            @helpers.avatar(comment.commentedUserName, 16)
            @helpers.user(comment.commentedUserName, styleClass="username strong")
            changed title from <code>@convertLineSeparator(comment.content, "LF").split("\n")(0)</code> to <code>@convertLineSeparator(comment.content, "LF").split("\n")(1)</code>
            @gitbucket.core.helper.html.datetimeago(comment.registeredDate)
          </div>
        </div>
      }
      case "change_base_branch" => {
        <div class="discussion-item discussion-item-pencil">
          <div class="discussion-item-header">
            <span class="discussion-item-icon"><i class="octicon octicon-pencil"></i></span>
            @helpers.avatar(comment.commentedUserName, 16)
            @helpers.user(comment.commentedUserName, styleClass="username strong")
            changed base branch from <code>@convertLineSeparator(comment.content, "LF").split("\n")(0)</code> to <code>@convertLineSeparator(comment.content, "LF").split("\n")(1)</code>
            @gitbucket.core.helper.html.datetimeago(comment.registeredDate)
          </div>
        </div>
      }
      case "delete_comment" => {
        <div class="discussion-item discussion-item-delete-comment">
          <div class="discussion-item-header">
            <span class="discussion-item-icon"><i class="octicon octicon-trashcan"></i></span>
            @helpers.avatar(comment.commentedUserName, 16)
            @helpers.user(comment.commentedUserName, styleClass="username strong")
            deleted the comment
            @gitbucket.core.helper.html.datetimeago(comment.registeredDate)
          </div>
        </div>
      }
      case _ => {
        @showFormattedComment(comment)
      }
    }
  }
  case comments: gitbucket.core.model.CommitComments => {
    @gitbucket.core.helper.html.commitcomments(comments, isManageable, repository, commitId.orElse(pullreq.map(_.commitIdTo)))
  }
  case comment: gitbucket.core.model.CommitComment => {
    <div class="panel panel-default commit-comment-box commit-comment-@comment.commentId">
      <div class="panel-heading">
        @helpers.avatarLink(comment.commentedUserName, 20)
        @helpers.user(comment.commentedUserName, styleClass="username strong")
        <span class="muted">
          commented
          <a href="#comment-@comment.commentId">@gitbucket.core.helper.html.datetimeago(comment.registeredDate)</a>
          on
          <a href="@helpers.url(repository)/commit/@comment.commitId" class="monospace">@comment.commitId.substring(0, 7)</a>
        </span>
        @if((isManageable || context.loginAccount.map(_.userName == comment.commentedUserName).getOrElse(false))){
          <span class="pull-right">
            <a href="#" data-comment-id="@comment.commentId"><i class="octicon octicon-pencil" aria-label="Edit"></i></a>&nbsp;
            <a href="#" data-comment-id="@comment.commentId"><i class="octicon octicon-x" aria-label="Remove"></i></a>
          </span>
        }
      </div>
      <div class="panel-body markdown-body commit-commentContent-@comment.commentId">
        @helpers.markdown(
          markdown           = comment.content,
          repository         = repository,
          branch             = repository.repository.defaultBranch,
          enableWikiLink     = false,
          enableRefsLink     = true,
          enableLineBreaks   = true,
          enableTaskList     = true,
          hasWritePermission = isManageable
        )
      </div>
    </div>
  }
}
@if(renderScript){
<script>
$(function(){
@if(issue.isDefined){
  $('.issue-comment-box i.octicon-pencil').click(function(){
    let id  = $(this).closest('a').data('comment-id');
    let url = '@helpers.url(repository)/issue_comments/_data/' + id;
    let $content = $('#commentContent-' + id);

    if(!id){
      id  = $(this).closest('a').data('issue-id');
      url = '@helpers.url(repository)/issues/_data/' + id;
      $content = $('#issueContent');
    }

    $.get(url, { dataType : 'html' }, function(data){
      $content.empty().html(data);
    });
    return false;
  });
  $('.issue-comment-box i.octicon-x').click(function(){
    if(confirm('Are you sure you want to delete this?')) {
      const id = $(this).closest('a').data('comment-id');
      $.post('@helpers.url(repository)/issue_comments/delete/' + id, function(data){
        if(data > 0) {
          $('#comment-' + id).remove();
        }
      });
    }
    return false;
  });
}
  $(document).on('click', '.commit-comment-box i.octicon-pencil', function(){
    const id  = $(this).closest('a').data('comment-id');
    const url = '@helpers.url(repository)/commit_comments/_data/' + id;
    const $content = $('.commit-commentContent-' + id, $(this).closest('.commit-comment-box'));

    $.get(url, { dataType : 'html' }, function(data){
      $content.empty().html(data);
    });

    return false;
  });

  $(document).on('click', '.commit-comment-box i.octicon-x', function(){
    if(confirm('Are you sure you want to delete this?')) {
      const id = $(this).closest('a').data('comment-id');
      $.post('@helpers.url(repository)/commit_comments/delete/' + id,
      function(data){
        if(data > 0) {
          const comment = $('.commit-comment-' + id);

          // diff view
          const tr = comment.closest('.not-diff');
          if(tr.length > 0){
            if(tr.prev('.not-diff').length == 0){
              tr.next('.not-diff:has(.reply-comment)').remove();
            }
            tr.remove();
          }

          // comment list view
          const panel = comment.closest('div.panel:has(.commit-comment-box)');
          if(panel.length > 0){
            comment.parent('.commit-comment-box').remove();
            if(panel.has('.commit-comment-box').length == 0){
              panel.remove();
            }
          } else {
            comment.remove();
          }
        }
      });
    }
    return false;
  });

  $('div[class*=commit-commentContent-]').on('click', ':checkbox', function(ev){
    const $commentContent = $(ev.target).parents('div[class*=commit-commentContent-]'),
        commentId = $commentContent.attr('class').match(/commit-commentContent-.+/)[0].replace(/commit-commentContent-/, ''),
        checkboxes = $commentContent.find(':checkbox');
    $.get('@helpers.url(repository)/commit_comments/_data/' + commentId, { dataType : 'html' },
      function(responseContent){
        $.ajax({
          url: '@helpers.url(repository)/commit_comments/edit/' + commentId,
          type: 'POST',
          data: {
            issueId : 0,
            content : applyTaskListCheckedStatus(responseContent, checkboxes)
          },
          success: function(data) {
            $('.commit-commentContent-' + commentId).html(data.content);
          }
        });
      }
    );
  });

@if(issue.isDefined){
  $('#issueContent').on('click', ':checkbox', function(ev){
    const checkboxes = $('#issueContent :checkbox');
    $.get('@helpers.url(repository)/issues/_data/@issue.get.issueId', { dataType : 'html' },
      function(responseContent){
        $.ajax({
          url: '@helpers.url(repository)/issues/edit/@issue.get.issueId',
          type: 'POST',
          data: {
            title   : $('#issueTitle').text(),
            content : applyTaskListCheckedStatus(responseContent, checkboxes)
          }
        });
      }
    );
  });

  $('div[id^=commentContent-]').on('click', ':checkbox', function(ev){
    const $commentContent = $(ev.target).parents('div[id^=commentContent-]'),
        commentId = $commentContent.attr('id').replace(/commentContent-/, ''),
        checkboxes = $commentContent.find(':checkbox');
    $.get('@helpers.url(repository)/issue_comments/_data/' + commentId, { dataType : 'html' },
      function(responseContent){
        $.ajax({
          url: '@helpers.url(repository)/issue_comments/edit/' + commentId,
          type: 'POST',
          data: {
            issueId : 0,
            content : applyTaskListCheckedStatus(responseContent, checkboxes)
          }
        });
      }
    );
  });
}
});
</script>
}
